package action;


import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import service.IProductService;
import service.ISaleService;
import vo.Employee;
import vo.Payment;
import vo.Product;
import vo.Saleorder;
import vo.Saleorderitem;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class SaleAction extends ActionSupport{
	private String name;
	private String password;
	private ISaleService saleService;
	private IProductService productService;
	private String saleorderid;
	
	private  int productid;
	private  int customerid;
	
	
	public String getSaleorderid() {
		return saleorderid;
	}
	public void setSaleorderid(String saleorderid) {
		this.saleorderid = saleorderid;
	}
	public int getCustomerid() {
		return customerid;
	}
	public void setCustomerid(int customerid) {
		this.customerid = customerid;
	}
	public int getProductid() {
		return productid;
	}
	public void setProductid(int productid) {
		this.productid = productid;
	}
	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	private  int quantity;
   
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public ISaleService getSaleService() {
		return saleService;
	}
	public void setSaleService(ISaleService saleService) {
		this.saleService = saleService;
	}
	
	public IProductService getProductService() {
		return productService;
	}
	public void setProductService(IProductService productService) {
		this.productService = productService;
	}
	//===================1.用户登录==========================================
    public String login(){
     Result result = new Result();
        try {
        	Employee employee=saleService.getEmployee(name,password);
        	 System.out.println("test3");
        	
        	result.setSuccess(true);
        	 System.out.println("test6");
            result.setMsg("登陆成功");
        	if(employee!=null){
        		 System.out.println("test7");
        		Map session=ActionContext.getContext().getSession();
        		session.put("employee", employee);
        	}
            
          
        } catch (Exception e) {
            result.setMsg("登录失败");
        }
        writeJson(result);
      return null;
    	
    }
  //===================2.创建订单==========================================
    public String addsaleorder(){
    	  Result result = new Result();
    	  Saleorder saleorder=new Saleorder();
          try {
        	  Map session=ActionContext.getContext().getSession();
        	  Employee employee=(Employee)session.get("employee");
        	String saleorderid1=new SimpleDateFormat("MMddmmss").format(Calendar.getInstance().getTime());
        	int saleorderid=Integer.parseInt(saleorderid1);
        	Timestamp datetime = new Timestamp(System.currentTimeMillis());
        	 System.out.println("创建订单7");
        	saleorder.setSaleorderid(saleorderid);
        	 System.out.println("创建订单8");
        	 saleorder.setCustomerid(customerid);
        	saleorder.setCreatdatetime(datetime);
        	saleorder.setEmployeeid(employee.getEmployeeid());
        	saleorder.setState("no");
        	  saleService.addSaleorder(saleorder);
              result.setSuccess(true);
              result.setMsg("创建订单成功");
          		session.put("saleorder", saleorder);
          	
          } catch (Exception e) {
              result.setMsg("创建订单失败");
          }
          writeJson(result);
          saleorder=new Saleorder();
          return null;
    }
  //===================3.添加订单明细表==========================================
    public String addsaleorderitem(){
    	  Map session=ActionContext.getContext().getSession();
    	  Saleorder saleorder1=(Saleorder)session.get("saleorder");
    	  
    	Product product=productService.getProductById(productid);
    	
    	Saleorderitem item=new Saleorderitem();
    	item.setSaleorderid(saleorder1.getSaleorderid());
    	item.setProductid(product.getProductId());
        item.setPrice(product.getPprice());
    	item.setQuantity(quantity);
    	
    	//=====显示=========================
    	Result result = new Result();
        try {
      	  saleService.addSaleorderitem(item);
      	float total=saleService.getTotalPrice();
            result.setSuccess(true);
        		session.put("total", total);
        		 result.setMsg("添加商品明细成功");
        } catch (Exception e) {
            result.setMsg("添加订单明细表失败");
        }
        writeJson(result);
        return null;
        
    }
    
    //===================4.显示订单明细表==========================================
    public String showitem(){
    	Map<String,Object>  map=new HashMap<String,Object>();
    	List<Saleorderitem> items=saleService.getAllItem();
        	map.put("total", 12);
        	map.put("rows", items);
        	writeJson(map);  
        	
        	
        	
        	return null;
       
    }
    //==============================5显示总金额=================================
    public String showtotalprice(){
    	
   	   
    	Map<String,Object>  map=new HashMap<String,Object>();
    	
      	
      	float total=saleService.getTotalPrice();
      	map.put("total",total);
       
		writeJson(map);
        return null;
        
       
    }
//=======6.结算===========================
      public String endsale(){
    	Map session=ActionContext.getContext().getSession();
    	Saleorder sa=(Saleorder) session.get("saleorder");
    	sa.setTotal(saleService.getTotalPrice());
    	sa.setState("yes");
    	Payment payment=new Payment();
    	String payid1=new SimpleDateFormat("yyyyMMddhhmmss").format(Calendar.getInstance().getTime());
    	String payid="pay-"+payid1;
    	Timestamp paytime = new Timestamp(System.currentTimeMillis());
    	
    	payment.setPayid(payid);
    	payment.setPaytime(paytime);
    	payment.setPaytotal(saleService.getTotalPrice());
    	payment.setPaytype("money");
    	payment.setSaleorderid(sa.getSaleorderid().toString());
    	
    	
    	Result result = new Result();
        try {	
        	 saleService.updateSaleorder(sa);
        	saleService.addPayment(payment);
        	session.remove("saleorder");
        	result.setMsg("结账成功");
        	 result.setSuccess(true);}
        catch (Exception e) {
            result.setMsg("结账失败");
        }
        writeJson(result);
    	return null;
    }   
  //=======7.挂账===========================
      public String quitsale(){
    	  Result result = new Result();
          try {	
          	Map session=ActionContext.getContext().getSession();

          	session.remove("saleorder");
          	result.setMsg("挂账成功");
          	 result.setSuccess(true);}
          catch (Exception e) {
              result.setMsg("挂账失败");
          }
          writeJson(result);
      	return null;

      }
    //================8.通过saleorderid获得所有订单明细===
    		public String getallitembyid(){
    			Map session=ActionContext.getContext().getSession();
        		session.put("saleorderid", saleorderid);
        		
    			Map<String,Object>  map=new HashMap<String,Object>();
    	    	List<Saleorderitem> items=saleService.getAllItemById(saleorderid);
    	        	map.put("total", 12);
    	        	map.put("rows", items);
    	        	writeJson(map);  
    	        	
    	        	saleorderid=null;
    	        	
    	        	return null;
    		}
    //===========================工具方法=========================
    public void writeJson(Object object) {
        try {         
        	JSONObject jsonObjectFromMap = JSONObject.fromObject(object);
        
        	String out=jsonObjectFromMap.toString();
          
            ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
            ServletActionContext.getResponse().getWriter().write(out);
            ServletActionContext.getResponse().getWriter().flush();
        } catch (IOException e) {
        	//productService.delProduct(product.getProductId());
            }
     
    }
	
	
    
}
